package com.doit.mr.day04.movie;

import com.alibaba.fastjson.JSON;
import com.doit.mr.day04.bean.MovieWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @DATE 2021/12/9/23:20
 * @Author MDK
 * @Version 2021.2.2
 * 求每部电影的平均分  K:id V:rate
 **/
public class AvgRate02 {
    //Mapper  K:movieID  V:rate
    //将自定义的类放在泛型中  自定义的类要实现HDP序列化
    static class AvgRate02Mapper extends Mapper<LongWritable, Text, Text, MovieWritable>{
        Text k = new Text();
        //每行执行一次
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String line = value.toString();
                //将行数据转化成movie 获取id,分数rate并封装起来
                MovieWritable movie = JSON.parseObject(line,MovieWritable.class);
                String uid = movie.getMovie();
                k.set(uid);
                context.write(k,movie);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //如果最终的输出结果不是电影均分的需求 而是电影的记录 输出的结果没必要K V  所以输出的可以是NullWritable  没有输出内容
    static class AvgRate02Reducer extends Reducer<Text, MovieWritable, Text, DoubleWritable>{
        DoubleWritable v = new DoubleWritable();

        @Override
        protected void reduce(Text key, Iterable<MovieWritable> values, Context context) throws IOException, InterruptedException {
            double sum = 0;
            int cnt = 0;
            for (MovieWritable value : values) {
                double rate = value.getRate();
                sum += rate;
                cnt++;
            }
            double avg = sum/cnt;
            v.set(avg);
            context.write(key,v);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "avgRate02");
        job.setMapperClass(AvgRate02Mapper.class);
        job.setReducerClass(AvgRate02Reducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(MovieWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        FileInputFormat.setInputPaths(job, new Path("D:\\mrdata\\movie\\input"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\mrdata\\movie\\avg_rate02"));
        job.waitForCompletion(true);
    }
}
